package me.ziry.util;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import me.ziry.ui.IndexUi;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AlertPhotoUtil {

    public int alterCount = 0;
    public int errorCount = 0;
    public int sum = 0;

    public List<String> errorNameList = new ArrayList<String>();


    /* 汉字转换成安卓资源的规则 */
    public String toAndroidRule(String chineseLanguage) {

        char[] cl_chars = chineseLanguage.trim().toCharArray();
        StringBuilder pinYin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部小写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        try {
            for (int i = 0; i < cl_chars.length; i++) {
                String str = String.valueOf(cl_chars[i]);
                if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音
                    pinYin.append(PinyinHelper.toHanyuPinyinStringArray(
                            cl_chars[i], defaultFormat)[0]);

                    pinYin.append("_");

                } else if (str.matches("[0-9]+") || str.matches("[a-z]+") || str.equalsIgnoreCase("_")) {// 如果数字或小写字母或下划线不管
                    pinYin.append(cl_chars[i]);
                } else {// 否则不转换
                    System.out.println("过滤了:" + cl_chars[i]);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }

        if (pinYin.lastIndexOf("_") != -1) {
            pinYin.deleteCharAt(pinYin.lastIndexOf("_"));
        }

        System.out.println(chineseLanguage + ":" + pinYin);

        return pinYin.toString();
    }

    /**
     * 汉字名 转拼音
     */
    public String getImgFilePinyin(File imgFile) {

        String oldName = imgFile.getPath().replace(IndexUi.startFile.getPath(), "");

        String name = toAndroidRule(oldName.substring(0, oldName.indexOf(".")));

        return name;
    }

    /**
     * 获取文件名以拍摄日期加随机数组成的文件名
     *
     * @param imgFile
     * @return
     * @throws JpegProcessingException
     * @throws IOException
     */
    public String getImgFileDate(File imgFile) {

        Directory exif = null;
        try {
            Metadata metadata = JpegMetadataReader.readMetadata(imgFile);
            exif = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
        } catch (JpegProcessingException | IOException e) {
//			e.printStackTrace();
        }

        String imgDate = null;

        if (exif != null) {
            imgDate = exif.getString(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
        }

        if (imgDate == null || imgDate.length() == 0) {

            long time = imgFile.lastModified();//返回文件最后修改时间，是以个long型毫秒数
            imgDate = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss").format(new Date(time));

			/*
			Date date=new Date();
			DateFormat format=new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
			imgDate = format.format(date);
			*/
        }
        imgDate = imgDate.replaceAll(":", "").replaceAll(" ", "_") + "_" + sum;
        return imgDate;
    }

    /**
     * 获取当前文件名后缀
     *
     * @param imgFile
     * @return
     */
    public String gerImgFileSuffix(File imgFile) {
        String imgname = imgFile.getName();
        return imgname.substring(imgname.lastIndexOf('.') + 1);
    }

    /**
     * 重名文件名
     *
     * @param imgFile
     * @param newname
     * @return
     */
    public boolean alterImgFileName(File imgFile, String newname) {
        String rootPath = imgFile.getParent();
        File newFile = new File(rootPath + File.separator + newname);
        return imgFile.renameTo(newFile);
    }

    public void start(File imgFile) {
        if (imgFile.isFile()) {
            sum++;
            try {
                this.alterImgFileName(imgFile, this.getImgFilePinyin(imgFile) + "." + this.gerImgFileSuffix(imgFile));
                alterCount++;
            } catch (Exception e) {
                errorNameList.add(imgFile.getName() + " error : " + e);
                e.printStackTrace();
                errorCount++;
            }
        } else {

            File[] tempList = imgFile.listFiles();
            for (int i = 0; i < tempList.length; i++) {
                this.start(tempList[i]);
            }

        }

    }
}
